/*
 * Copyright 2013-2018 Lilinfeng.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intelligent.mts.da.server;


import com.google.common.collect.Lists;
import com.intelligent.mts.core.utils.AppConst;
import com.intelligent.mts.da.xmlmessage.HttpXmlRequest;

import com.intelligent.mts.da.handler.UpdateStatusHandler;
import com.intelligent.mts.da.handler.ValidateHandler;
import com.intelligent.mts.da.message.ReceiveMessage;
import com.intelligent.mts.da.utils.MessageUtils;
import com.intelligent.mts.da.xmlmessage.Validate;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;

import java.util.List;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

public class HttpXmlServerHandler extends
		SimpleChannelInboundHandler<HttpXmlRequest> {


	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		cause.printStackTrace();
		if (ctx.channel().isActive()) {
			sendError(ctx, INTERNAL_SERVER_ERROR);
		}
	}

	private static void sendError(ChannelHandlerContext ctx,
								  HttpResponseStatus status) {
		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
				status, Unpooled.copiedBuffer("失败: " + status.toString()
				+ "\r\n", CharsetUtil.UTF_8));
		response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8");
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}

	@Override
	protected void channelRead0(final ChannelHandlerContext ctx, HttpXmlRequest xmlRequest) throws Exception {

		if (!(xmlRequest.getBody() instanceof  Validate) && "WSDL".equalsIgnoreCase((String) xmlRequest.getBody())){

			Validate validate = new Validate();
			validate.setService("ExampleService");
			validate.setInfo("ExampleInfo");
			ctx.fireChannelRead(validate);
			return;
		}

		Validate validate = (Validate) xmlRequest.getBody();

		List<String> resultLists = Lists.newArrayList();
		ReceiveMessage receiveMessage = new ReceiveMessage();
		ChannelPipeline p = ctx.pipeline();
		if (AppConst.GetProgNameByBatch.equals(validate.getService())){
			String message1 = "1010;";
			message1 += validate.getInfo();
			receiveMessage = MessageUtils.decodeMessage(message1);
//			resultLists = ApplicationBeanUtils.getBean(ValidateHandler.class).saveSN(receiveMessage);
//            p.addLast("validateHandler", new ValidateHandler());
			p.addAfter("xmlServerHandler","validateHandler",new ValidateHandler());
            ctx.fireChannelRead(receiveMessage);
		}else if (AppConst.SendTestResult.equals(validate.getService())){
			String message1 = "2010;";
			message1 += validate.getInfo();
			receiveMessage = MessageUtils.decodeMessage(message1);
            p.addAfter("xmlServerHandler","updateStatusHandler", new UpdateStatusHandler());
            ctx.fireChannelRead(receiveMessage);
		}

		System.out.println("Http server receive request : " + validate);

//		validateReturnMsg validateReturnMsg = new validateReturnMsg();
//		validateReturnMsg.setService("SendTestResult");
//		validateReturnMsg.setResult("NG");
//		validateReturnMsg.setInfo("FCT for CA 20160831/获取程序失败，请确定SN是否填写正确");
//		ChannelFuture future = ctx.writeAndFlush(new HttpXmlResponse(null, validateReturnMsg));
//		if (!isKeepAlive(request)) {
//			future.addListener(new GenericFutureListener<Future<? super Void>>() {
//				public void operationComplete(Future future) throws Exception {
//					ctx.close();
//				}
//			});
//		}
	}
}
